"""
    多头注意力
"""
import tensorflow as tf
from .common_function import scaled_dot_product_attention


class MultiHeadAttention(tf.keras.layers.Layer):
    # 初始化函数
    def __init__(self, d_model, num_heads):
        """
        参数
            d_model -> encoder和decoder的隐藏维度   类型->整数
            num_heads -> 多头注意力的头数  类型->整数
        """
        # 继承父类方法和属性
        super(MultiHeadAttention, self).__init__()
        # 初始化注意力头数
        self.num_heads = num_heads
        # encoder和decoder的隐藏维度
        self.d_model = d_model
        # 隐藏维度必须能整数多头注意力头数
        assert d_model % self.num_heads == 0

        self.depth = d_model // self.num_heads
        # query矩阵
        self.wq = tf.keras.layers.Dense(d_model)
        # key矩阵
        self.wk = tf.keras.layers.Dense(d_model)
        # value矩阵
        self.wv = tf.keras.layers.Dense(d_model)
        # 定义输出层
        self.dense = tf.keras.layers.Dense(d_model)

    # 拆分注意力头 方法
    def split_heads(self, x, batch_size):
        """分拆最后一个维度到 (num_heads, depth).
        转置结果使得形状为 (batch_size, num_heads, seq_len, depth)
        """
        x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
        return tf.transpose(x, perm=[0, 2, 1, 3])

    # 定义执行函数
    def call(self, v, k, q, mask):
        batch_size = tf.shape(q)[0]

        q = self.wq(q)  # (batch_size, seq_len, d_model)
        k = self.wk(k)  # (batch_size, seq_len, d_model)
        v = self.wv(v)  # (batch_size, seq_len, d_model)

        q = self.split_heads(q, batch_size)  # (batch_size, num_heads, seq_len_q, depth)
        k = self.split_heads(k, batch_size)  # (batch_size, num_heads, seq_len_k, depth)
        v = self.split_heads(v, batch_size)  # (batch_size, num_heads, seq_len_v, depth)

        # scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth)
        # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k)
        scaled_attention, attention_weights = scaled_dot_product_attention(
            q, k, v, mask)

        scaled_attention = tf.transpose(scaled_attention,
                                        perm=[0, 2, 1, 3])  # (batch_size, seq_len_q, num_heads, depth)

        concat_attention = tf.reshape(scaled_attention,
                                      (batch_size, -1, self.d_model))  # (batch_size, seq_len_q, d_model)

        output = self.dense(concat_attention)  # (batch_size, seq_len_q, d_model)

        return output, attention_weights

